package com.geekstudy.week12;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class ActiveMQJMSQueueDemo {

    public static void main(String[] args) {
        String queueUrl = "tcp://127.0.0.1:61616";
        String queueName = "demo.java4.queue";

        try {

            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
                    ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, queueUrl
            );
            Connection connection = connectionFactory.createConnection();
            connection.start();
            Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            Destination destinationQueue = session.createQueue(queueName);

            // 创建 发送者
            MessageProducer messageProducer = session.createProducer(destinationQueue);
            messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT);
            String message = "hello Queue 的测试";
            TextMessage textMessage = session.createTextMessage(message);
            messageProducer.send(textMessage);
            System.out.println("send message success");
            session.commit();
            // SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
            // SLF4J: Defaulting to no-operation (NOP) logger implementation
            // SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

            // 创建 接受者
            MessageConsumer messageConsumer = session.createConsumer(destinationQueue);
            Message receiveMessage = messageConsumer.receive(1000 * 10);
            if(receiveMessage == null) {
                System.out.println("receiveMessage is null " );
            }
            if(receiveMessage instanceof TextMessage) {
                TextMessage receiveTextMessage = (TextMessage)receiveMessage;
                System.out.println("收到消息:" + receiveTextMessage.getText());
            }
            session.commit();
            System.out.println("receive message success!");

            session.close();
            connection.close();





        } catch(Exception e) {
            e.printStackTrace();
        }


    }
}
